package com.lxl.xm.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lxl.xm.common.BaseResponse;
import com.lxl.xm.common.DailyEarning;
import com.lxl.xm.common.ResultUtils;
import com.lxl.xm.exception.BusinessException;
import com.lxl.xm.model.entity.Revenue;
import com.lxl.xm.model.vo.RevenueVO;

import com.lxl.xm.service.RevenueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@RestController
@RequestMapping("/revenue")
@Slf4j
public class RevenueController {
    @Resource
    RevenueService revenueService;

    @PostMapping("/create")
    public BaseResponse<Revenue>createRevenue(@RequestBody RevenueVO revenueVO){
        try{
            Revenue revenue = revenueService.createOrUpdateRevenue(revenueVO);
            return ResultUtils.success(revenue);
        }catch (BusinessException e){
            return ResultUtils.error(500,e.getMessage());
        }
    }
    @GetMapping("/{id}")
    public BaseResponse<Revenue> getRevenue(@PathVariable Long id) {
        try {
            Revenue revenue = revenueService.getRevenueById(id);
            if (revenue != null) {
                return ResultUtils.success(revenue);
            } else {
                return ResultUtils.error(404, "Revenue not found");
            }
        } catch (BusinessException e) {
            return ResultUtils.error(500, "Internal Server Error: " + e.getMessage());
        }
    }

    @PutMapping("/update")
    public BaseResponse<Revenue> updateRevenue(@RequestBody RevenueVO revenueVO) {
        try {
            Revenue revenue = revenueService.createOrUpdateRevenue(revenueVO);
            return ResultUtils.success(revenue);
        } catch (BusinessException e) {
            return ResultUtils.error(500, "Internal Server Error: " + e.getMessage());
        }
    }

    @DeleteMapping("/delete/{id}")
    public BaseResponse<Void> deleteRevenue(@PathVariable Long id) {
        try {
            boolean deleted = revenueService.deleteRevenue(id);
            if (deleted) {
                return ResultUtils.success(null);
            } else {
                return ResultUtils.error(404, "Revenue not found or already deleted");
            }
        } catch (BusinessException e) {
            return ResultUtils.error(500, "Internal Server Error: " + e.getMessage());
        }
    }


    @GetMapping("/last-seven-days")
    public BaseResponse<List<DailyEarning>>getRevenueLastSevenDays(){
        //初版BUG：不能计算每天的总收益
//        LocalDate sevenDayAgo = LocalDate.now().minusDays(6);
//        QueryWrapper<Revenue> queryWrapper = new QueryWrapper<>();
//        queryWrapper.ge("date",sevenDayAgo);
//        queryWrapper.orderByAsc("date");
//        List<Revenue>revenueList = revenueService.list(queryWrapper);
//        List<DailyEarning>dailyEarningsList = revenueList.stream()
//                .map(revenue -> new DailyEarning(revenue.getDate(),revenue.getEarnings()))
//                .collect(Collectors.toList());
//        return ResultUtils.success(dailyEarningsList);

            //version2 没有收益的那天不会返回
//        LocalDate sevenDayAgo = LocalDate.now().minusDays(6);
//        QueryWrapper<Revenue> queryWrapper = new QueryWrapper<>();
//        queryWrapper.ge("date", sevenDayAgo);
//        queryWrapper.orderByAsc("date");
//        List<Revenue> revenueList = revenueService.list(queryWrapper);
//
//        Map<LocalDate, Double> dailyEarningsMap = revenueList.stream()
//                .collect(Collectors.groupingBy(Revenue::getDate,
//                        Collectors.summingDouble(Revenue::getEarnings)));
//
//        List<DailyEarning> dailyEarningsList = dailyEarningsMap.entrySet().stream()
//                .map(entry -> new DailyEarning(entry.getKey(), entry.getValue()))
//                .collect(Collectors.toList());
//
//        return ResultUtils.success(dailyEarningsList);

        LocalDate sevenDayAgo = LocalDate.now().minusDays(6);
        Map<LocalDate, Double> dailyEarningsMap = IntStream.rangeClosed(0, 6)
                .mapToObj(i -> sevenDayAgo.plusDays(i))
                .collect(Collectors.toMap(Function.identity(), v -> 0.0));

        QueryWrapper<Revenue> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("date", sevenDayAgo);
        queryWrapper.orderByAsc("date");
        List<Revenue> revenueList = revenueService.list(queryWrapper);

        revenueList.forEach(revenue -> dailyEarningsMap.merge(
                revenue.getDate(), revenue.getEarnings(), Double::sum));

        List<DailyEarning> dailyEarningsList = dailyEarningsMap.entrySet().stream()
                .map(entry -> new DailyEarning(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());

        return ResultUtils.success(dailyEarningsList);
    }

    @GetMapping("today")
    public BaseResponse<Double>getTodayRevenue(){
        LocalDate today = LocalDate.now();
        QueryWrapper<Revenue>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("date",today);
        List<Revenue>revenueList=revenueService.list(queryWrapper);
        double todayEarnings = revenueList.stream()
                .mapToDouble(Revenue::getEarnings)
                .sum();
        return ResultUtils.success(todayEarnings);
    }

    @GetMapping("total")
    public BaseResponse<Double>getTotalRevenue(){
        List<Revenue>revenueList = revenueService.list(new QueryWrapper<>());
        double totalEarnings = revenueList.stream()
                .mapToDouble(Revenue::getEarnings)
                .sum();
        return ResultUtils.success(totalEarnings);
    }
}
